const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const couponService = require('../../services/good/couponService');
class CouponController {
    static async getCouponList(ctx) {
        const requestData = ctx.request.body || {};
        const { pageNum = 1, pageSize = 10 } = requestData;
        // 提取查询条件，排除分页参数
        const queryData = { ...requestData };
        delete queryData.pageNum;
        delete queryData.pageSize;
        
        const res = await couponService.getCouponList({ pageNum, pageSize }, queryData);
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }
    static async getCouponById(ctx) {
        const { id: couponId } = ctx.request.body;
        const res = await couponService.getCouponById(couponId);
        res ? response.success(ctx, { data: res }) : response.error(ctx, { message: '优惠券不存在'});
    }
    static async createCoupon(ctx) {
        const couponData = ctx.request.body;
        if (couponData.discountType === 'percentage') {
            // 如果是百分比折扣，确保 discountValue 是一个百分比值 小于等于1
            if (couponData.discountValue > 1) {
                return response.error(ctx, { message: '折扣率必须小于等于1' });
            }
        } else {
            // 如果是固定金额折扣，确保 discountValue 是数字
            const discountValue = parseFloat(couponData.discountValue);
            if (isNaN(discountValue)) {
                return response.error(ctx, { message: '折扣值必须是有效数字' });
            }
            couponData.discountValue = discountValue;
        }

        try {
            const result = await couponService.createCoupon(couponData);
            response.success(ctx, { data: result });
        } catch (err) {
            handleDatabaseError(ctx, err, '创建优惠券失败');
        }
    }
    static async updateCoupon(ctx) {
        const couponData = ctx.request.body;
        if (couponData.discountType === 'percentage') {
            // 如果是百分比折扣，确保 discountValue 是一个小于等于1的值
            if (couponData.discountValue > 1) {
                return response.error(ctx, { message: '折扣率必须小于等于1' });
            }
        } else {
            // 如果是固定金额折扣，确保 discountValue 是数字
            const discountValue = parseFloat(couponData.discountValue);
            if (isNaN(discountValue)) {
                return response.error(ctx, { message: '折扣值必须是有效数字' });
            }
            couponData.discountValue = discountValue;
        }

        try {
            const result = await couponService.updateCoupon(couponData);
            response.success(ctx, { data: result });
        } catch (err) {
            handleDatabaseError(ctx, err, '更新优惠券失败');
        }
    }
    static async deleteCoupon(ctx) {
        const { id: couponId } = ctx.request.body;
        const res = await couponService.deleteCoupon(couponId);
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }
} module.exports = CouponController;
